package com.example.feidaolumanager.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.feidaolumanager.api.RetrofitClient
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody


class FileUploadViewModel : ViewModel() {

    private val TAG: String = this.toString()

    // 当前上传的是那张照片
    var currentUploadImageIndex: Int = 0


    var uploadImagePath: MutableLiveData<String?> = MutableLiveData(null)

    fun fileUpload(imageBytes: ByteArray, imageName: String?) {
        Log.e(TAG, "fileUpload: $imageName")

        val imageBody: RequestBody =
            imageBytes.toRequestBody("multipart/form-data".toMediaTypeOrNull(), 0, imageBytes.size)
        val formData =
            MultipartBody.Part.createFormData("lemonFile", filename = imageName, imageBody)

        viewModelScope.launch {

            val filePath = RetrofitClient.fileUploadService.fileUpload(formData)

            uploadImagePath.value = filePath

            Log.e(TAG, "fileUpload: $filePath")
        }
    }

}